package binfa;

public class sisuo {
    private static Object resource1 = new Object();//资源 1
    private static Object resource2 = new Object();//资源 2
    public static void main(String[] args) {
       new Thread(()->{
           synchronized (resource1){
               System.out.println("我是"+resource1);
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               synchronized (resource2){
                   System.out.println("我是"+resource2);
               }
           }
       }).start();
       new  Thread(()->{
           synchronized (resource2){
               System.out.println("我是"+resource2);
               try {
                   Thread.sleep(2000);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
               synchronized (resource1){
                   System.out.println("我是"+resource1);
               }
           }
       }).start();
       //解决死锁办法：按照一定的顺序进行加锁,不要出现循环加锁的过程
//        new Thread(()->{
//            synchronized (resource1){
//                System.out.println("我是"+resource1);
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                synchronized (resource2){
//                    System.out.println("我是"+resource2);
//                }
//            }
//        }).start();
//        new  Thread(()->{
//            synchronized (resource1){
//                System.out.println("我是"+resource1);
//                try {
//                    Thread.sleep(2000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                synchronized (resource2){
//                    System.out.println("我是"+resource2);
//                }
//            }
//        }).start();
    }
}
